var salt = sessionStorage.getItem('usersalt');

layui.use(['form', 'layer', 'laydate', 'table'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		laydate = layui.laydate,
		formSelects = layui.formSelects,
		table = layui.table;

	/*验证登录*/
	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}

	/*时间选择器*/
	laydate.render({
		elem: '#statdate',
		trigger: 'click'
	});

	laydate.render({
		elem: '#enddate',
		trigger: 'click'
	});

	/*筛选*/
	$('#seleJsa').on('click', function() {
		getJsaAnalyzeList();
	});

	/*搜索*/
	$('#findscri').on('click', function() {
		var inptext = $('#inptext').val();
		var box = /\s/g;
		var param = inptext.replace(box, '');
		getJsaAnalyzeList(param);
	});
	
	var company;
	/*取出所有的单位*/
	function getAllDanwei() {
		$.ajax({
			url: url + 'baseEnt/getAllEnt',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {
			},
			success: function(data) {
				$('#workEntTree').empty();
				$('#writeEntTree').empty();
				if(data.code == 0) {
					var list = data.data;
					company = list;
				}
			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	}
	getAllDanwei();

	/*------------tree.start------------*/
	var setting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onCheck: zTreeOnCheck
		}
	};
	var zNodes = company;
	$.fn.zTree.init($("#workEntTree"), setting, zNodes);
	function getWorkEntVal() {
		var treeArr = [];
		var treeObj = $.fn.zTree.getZTreeObj("workEntTree");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			treeArr.push(nodes[i].id); //获取选中节点的值
		}
		return treeArr;
	}
	$('#workEnt').click(function() {
		$("body").trigger("click");
		$('#workEntTree').show();
	});
	function zTreeOnCheck(event, treeId, treeNode) {
		var nval = "";
		var treeObj = $.fn.zTree.getZTreeObj("workEntTree");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			nval += nodes[i].name + ",";
		}
		$('#workEnt').val(nval.substr(0, nval.length - 1));
	};
	/*------------tree.end------------*/
	
	/*------------tree.start------------*/
	var setting1 = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onCheck: zTreeOnCheck1
		}
	};
	$.fn.zTree.init($("#writeEntTree"), setting1, zNodes);
	function getWriteEntVal() {
		var treeArr = [];
		var treeObj = $.fn.zTree.getZTreeObj("writeEntTree");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			treeArr.push(nodes[i].id); //获取选中节点的值
		}
		return treeArr;
	}
	$('#writeEnt').click(function() {
		$("body").trigger("click");
		$('#writeEntTree').show();
	});
	function zTreeOnCheck1(event, treeId, treeNode) {
		var nval = '';
		var treeObj = $.fn.zTree.getZTreeObj("writeEntTree");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			nval += nodes[i].name + ",";
		}
		$('#writeEnt').val(nval.substr(0, nval.length - 1));
	};
	/*------------tree.end------------*/

	var tableIns;
	//安全检查列表
	function getJsaAnalyzeList(searchText) {
		var workEntArr = getWorkEntVal();
		var writeEntArr = getWriteEntVal();
		if(!searchText) {
			searchText = null;
		}

		tableIns = table.render({
			elem: '#jsaList',
			method: 'post',
			url: url + 'jsaAnalyze/getPage',
			where: {
				Token: salt, //用户码
				searchText: searchText, //搜索文本框内容
				workEntIds: workEntArr.toString(), //作业单位ids
				writeEntIds: writeEntArr.toString(), //填写单位ids
				startTime: $('#statdate').val(), //开始时间
				endTime: $('#enddate').val(), //结束时间
			},
			cellMinWidth: 95,
			page: true,
			height: "full-115",
			id: "jsaListTable",
			cols: [
				[
					{type: "numbers", width: 50, title: "序号"},
					{type: "checkbox", width: 50},
					{field: 'task', title: '工作任务', align: 'center', templet: function(p) {
							if (p.task == null) {
								return "<div></div>";
							} else {
								var acronymTask = p.task.length < 20 ? p.task : (p.task.substring(0, 20) + "...");
								return "<div id=\"" + p.id + "\" title=\""+ p.task.split("\n").toString()+"\"" +
									"onclick=showDetail('" + p.id + "')>" + acronymTask + "</div>";
							}
						}
					},
					{field: 'recordNumber', title: '记录编号', align: 'center', templet: function(p) {
							if (p.recordNumber == null) {
								return "<div></div>";
							} else {
								return "<div onclick=showDetail('" + p.id + "')>" + p.recordNumber + "</div>";
							}
						}
					},
					{field: 'workEntName', title: '作业单位', align: 'center', templet: function(p) {
							if (p.workEntName == null) {
								return "<div></div>";
							} else {
								return "<div onclick=showDetail('" + p.id + "')>" + p.workEntName + "</div>";
							}
						}
					},
					{field: 'userEntName', title: '填写单位', align: 'center', templet: function(p) {
							if (p.userEntName == null) {
								return "<div></div>";
							} else {
								return "<div onclick=showDetail('" + p.id + "')>" + p.userEntName + "</div>";
							}
						}
					},
					{field: 'workTime', title: '作业日期', align: 'center', templet: function(p) {
							if(p.workTime == null) {
								return "<div></div>";
							} else {
								return "<div onclick=showDetail('" + p.id + "')>" + p.workTime + "</div>";
							}
						}
					},
					{field: 'crtTime', title: '创建日期', align: 'center', templet: function(p) {
							if(p.crtTime == null) {
								return "<div></div>";
							} else {
								return "<div onclick=showDetail('" + p.id + "')>" + p.crtTime + "</div>";
							}
						}
					}
				]
			],
			done: function(res, curr, count) {
				//无论是异步请求数据，还是直接赋值数据，都会触发该回调。可以利用该回调做一些表格以外元素的渲染。
				//如果是异步请求数据方式，res即为你接口返回的信息。
				//如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
				//console.log(res.data);
				//得到当前页码
				//console.log(curr);
				//得到数据总量
				//console.log(count);
			}
		});

	}
	getJsaAnalyzeList();
	
	//编辑
	$(".edit_btn").click(function() {
		var checkStatus = table.checkStatus('jsaListTable'),
			data = checkStatus.data,
			editId = "";
			
		if (data.length > 1) {
			layer.msg("只能选择一条数据");
			return;
		}
		if( data[0].userId!=salt){
			layer.msg("只能编辑本人发起的数据");
			return;
		}
		
		if(data.length > 0) {
			editId = data[0].id;
			location.href = '../add/add.html?id=' + editId;
		} else {
			layer.msg("请选择需要编辑的数据");
		}
	});

	//批量删除
	$(".delAll_btn").click(function() {
		var checkStatus = table.checkStatus('jsaListTable'),
			data = checkStatus.data;
		
		var deleteIdArr = new Array();
		for(var i = 0; i < data.length; i++) {
			deleteIdArr.push(data[i].id);
		}
		if(data.length > 0) {
			layer.confirm('确定删除选中的数据吗？', {
				icon: 3,
				title: '提示信息'
			}, function(index) {
				$.ajax({
					url: url + 'jsaAnalyze/delAnalyze',
					dataType: 'json',
					async: false,
					type: "POST",
					data: {
						Token: salt,
						ids: deleteIdArr.toString()
					},
					success: function(data) {
						console.log(data);
						if(data.code == 0) {
							layer.msg('删除成功');
						} else {
							layer.msg(data.msg);
						}

					},
					error: function(error) {
						console.log("获取失败");
					}
				});

				tableIns.reload();
				layer.close(index);
			})
		} else {
			layer.msg("请选择需要删除的数据");
		}
	});
});

function showDetail(checkId) {
	location.href = '../detail/detail.html?id=' + checkId;
}

function showAllTask(self, cont) {
	layui.use(['layer', 'form'], function() {
		var layer = layui.layer;
		layer.tips(cont.split(",").join("<br/>"), "#" + self, {
			tips: [1, '#ccc'],
			time: 10000,
			area: ['auto', 'auto'] //这个属性可以设置宽高  auto 表示自动
		});
	});
}

function hideAllTask() {
	layer.closeAll();
}
